//
//  HDApplyIndemnitySecondVC.swift
//  HuaDaoPeifu
//
//  Created by ZERO on 2018/7/20.
//  Copyright © 2018年 paiyipai. All rights reserved.
//

import UIKit
import SVProgressHUD

class HDApplyIndemnitySecondVC: UIViewController, HNdatePickerDelagate, SinglePickerViewDelegate {

    
    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var typeLabel: UILabel!
    @IBOutlet weak var outTimeLabel: UILabel!
    @IBOutlet weak var hospitalTF: UITextField!
    @IBOutlet weak var diseaseTF: UITextField!
    
    @IBOutlet weak var totalPriceTF: UITextField!
    @IBOutlet weak var limitLabel: UILabel!
    
    @IBOutlet weak var thingsView: UIView!
    @IBOutlet weak var placeTF: UITextField!
    @IBOutlet weak var courseTV: UITextView!
    @IBOutlet weak var lastBtn1: UIButton!
    @IBOutlet weak var nextBtn2: UIButton!
    
    var picker: SinglePickerView!
    var bgView :UIView?
    lazy var pickerView: HNDateTimerPickerView = {
        guard let pickerView = HNDateTimerPickerView.newInstance() else {
            return HNDateTimerPickerView()
        }
        return pickerView
    }()
    
    
    
    var casemodel = HDCaseModel()
    var policyno = String()
    var info_id = String()
    var claim_type = String()  // 理赔id
    var recognizeeModel = HDRecognizeeModel()
    var partone = HDRecognizeeDetailModel()

    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        title = "速赔宝"
        setUI()
        dataRequest()

    }
     func setUI(){
        
        scrollView.contentSize = CGSize(width: 0, height: 850)

        let rightItem = UIBarButtonItem(title: "保单详情", style: .plain, target: self, action: #selector(rightItemAction))
        rightItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: UIControlState.normal)
        navigationItem.rightBarButtonItem = rightItem
        
        nextBtn2.layer.cornerRadius = 3
        lastBtn1.layer.cornerRadius = 3
        picker                 = SinglePickerView()
        picker?.type = SingleListType(rawValue: 2)!
        picker?.delegate            = self
    }
    
    
    func dataRequest() {
        limitLabel.text =  String(format: "（此次理赔申请额度为：%d）",casemodel.maxfee)
        HDApiManagerHandler.requestParttwo(casemodel.case_id, info_id, { (result2) in
            guard let result = result2 else{
                SVProgressHUD .showError("哦，网络出错了！")
                return
            }
            self.recognizeeModel = result
            self.recognizeeModel.partone = self.partone
            
            if self.recognizeeModel.parttwo != nil {
                self.claim_type = (self.recognizeeModel.parttwo?.claim_type)!
                self.typeLabel.text = self.getClaimName(claim_type: (self.recognizeeModel.parttwo?.claim_type) ?? "")
                self.outTimeLabel.text = self.recognizeeModel.parttwo?.claim_time
                self.hospitalTF.text = self.recognizeeModel.parttwo?.hospital
                self.totalPriceTF.text = self.recognizeeModel.parttwo?.total_money
                self.placeTF.text = self.recognizeeModel.parttwo?.claim_address
                self.diseaseTF.text = self.recognizeeModel.parttwo?.disease
                self.courseTV.text = self.recognizeeModel.parttwo?.accident_process
            }
           
            
            
        })
            
    }
    
    // 根据ID返回理赔类型
    func getClaimName(claim_type:String) -> String  {
        if claim_type == "1" {
            thingsView.isHidden = true
            return "疾病"
        }else {
            thingsView.isHidden = false
            return "意外"
        }
    }
    
    // 保单详情
    func rightItemAction(){
        let vc = HDPolicyDetailVC()
        vc.policynoStr = self.policyno
        navigationController?.pushViewController(vc, animated: true)
    }
    
    
    // 理赔类型
    @IBAction func typeSelect(_ sender: UIButton) {
        picker?.showInView()
    }
    func complete(_ pickerView: UIView!, tempStr str: String!, idStr idstr: String!) {
        if str == "意外" {
            thingsView.isHidden = false
        }else{
            thingsView.isHidden = true
        }
        typeLabel.text = str
        claim_type = (idstr! as NSString) as String
    }
    // 出险时间
    @IBAction func outTimeAction(_ sender: UIButton) {
        self.pickerView.delegate = self
        bgView = UIView()
        bgView?.frame = self.view.bounds
        bgView?.backgroundColor = UIColor(white: 0.1, alpha: 0.6)
        
        UIApplication.shared.keyWindow?.addSubview(bgView!)
        
        self.pickerView.frame = CGRect(x: 0, y: self.view.frame.height, width:self.view.frame.width, height: 0)
        UIView.animate(withDuration: 0.25, animations: {
            self.pickerView.frame = CGRect(x: 0, y: AppConstant.screenHeight - 280, width: self.view.frame.width, height: 280)
        })
        UIApplication.shared.keyWindow?.addSubview(self.pickerView)
        
        // 添加移除手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideView))
        bgView?.addGestureRecognizer(tapGesture)
    }
    // 移除动画
    func hideView() {
        UIView.animate(withDuration: 0.3) {
            self.pickerView.frame = CGRect(x:0,y:self.view.frame.height,width:self.view.frame.width,height:0)
            self.pickerView.removeFromSuperview()
            self.bgView?.removeFromSuperview()
        }
    }
    
    /// mark: HNdatePickerDelagate 完成
    func finishBtnAction(date: String) {
        print(date)
        self.outTimeLabel?.text = date
        self.hideView()
    }
    
    /// mark: HNdatePickerDelagate 取消
    func hideDataTimePickerView() {
        self.hideView()
    }
    
    @IBAction func lastStep1Action(_ sender: UIButton) {
        navigationController?.popViewController(animated: true)
    }
    
    @IBAction func nextStepAction(_ sender: UIButton) {
        
        if typeLabel.text == nil || typeLabel.text == "请选择" {
            SVProgressHUD.showError("请选择理赔类型")
            return
        }
        if outTimeLabel.text == nil || outTimeLabel.text == "请选择" {
            SVProgressHUD.showError("请选择出险时间")
            return
        }
        
        if totalPriceTF.text == nil || totalPriceTF.text == "" {
            SVProgressHUD.showError(totalPriceTF.placeholder!)
            return
        }
        if placeTF.text == nil || placeTF.text == "" {
            SVProgressHUD.showError(placeTF.placeholder!)
            return
        }
        
        if thingsView.isHidden == false && (courseTV.text == nil || courseTV.text == "") {
            SVProgressHUD.showError("请描述事故经过")
            return
        }
        
        if let value = self.totalPriceTF.text?.floatValue {
            if value >  Float(casemodel.maxfee){
                SVProgressHUD.showError(String(format: "（您最高可申请的赔付金额为：%d元）",casemodel.maxfee))
                return
            }
        }
        
        let model = HDParttwoModel()
        model.claim_type = self.claim_type
        model.claim_time = self.outTimeLabel.text!
        model.hospital = self.hospitalTF.text!
        model.disease = self.diseaseTF.text!
        model.total_money = self.totalPriceTF.text!
        model.claim_address = self.placeTF.text!
        model.accident_process = self.courseTV.text!
        recognizeeModel.parttwo = model
        
        HDApiManagerHandler.updateParttwo(casemodel.case_id, info_id, recognizeeModel.parttwo!) {[unowned self] (result:HDApiResult?) in
            guard let result = result else {
                SVProgressHUD.showError("网络开小差了，请一会再试...")
                return // 请求异常
            }
            if result.status == .Success{
                // self.casemodel  self.recognizeeModel.id
                // 第三步
                let vc = HDApplyIndemnityThreeVC.init(style: UITableViewStyle.grouped)
                vc.caseModel = self.casemodel
                vc.recognizee = self.recognizeeModel
                vc.policyno = self.policyno
                vc.info_id = self.info_id
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
